package top.jfunc.common.multipart;

import org.springframework.web.multipart.MultipartFile;
import top.jfunc.common.http.base.MediaType;
import top.jfunc.common.utils.IoUtil;

import java.io.*;
import java.nio.file.Files;

public class DiskFileMultipartFile implements MultipartFile {

    private final File file;
    private String contentType;

    public DiskFileMultipartFile(File file) {
        this.file = file;
        this.contentType = MediaType.APPLICATION_OCTET_STREAM_STRING;
    }
    public DiskFileMultipartFile(File file, String contentType) {
        this.file = file;
        this.contentType = contentType;
    }
    public DiskFileMultipartFile(File file, boolean autoDetectContentType, String defaultContentType) {
        this.file = file;
        if(autoDetectContentType){
            try {
                String probeContentType = Files.probeContentType(file.toPath());
                this.contentType = null!=probeContentType ? probeContentType : defaultContentType;
            } catch (IOException e) {
                this.contentType = defaultContentType;
            }
        }else {
            this.contentType = defaultContentType;
        }
    }

    @Override
    public String getName() {
        return file.getName();
    }

    @Override
    public String getOriginalFilename() {
        return file.getName();
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return file.length() == 0;
    }

    @Override
    public long getSize() {
        return file.length();
    }

    @Override
    public byte[] getBytes() throws IOException {
        return toByteArray(file);
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return Files.newInputStream(file.toPath());
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        if (!dest.exists()) {
            dest.createNewFile();
        }
        try (FileInputStream fis = new FileInputStream(file);
             FileOutputStream fos = new FileOutputStream(dest)) {
            IoUtil.copy(fis, fos);
        }
    }

    private byte[] toByteArray(File file) throws IOException {
        try (FileInputStream fis = new FileInputStream(file)) {
            return IoUtil.stream2Bytes(fis);
        }

    }


    public static MultipartFile from(File file) {
        return new DiskFileMultipartFile(file);
    }
    public static MultipartFile from(File file, String contentType) {
        return new DiskFileMultipartFile(file, contentType);
    }
}
